import {validatenull} from './validate'
import store from '@/store'
import router from '@/router'
import {relation} from '@/api/mail/write'
import calendar from '../../public/cdn/json/calendar'
import {Message} from 'element-ui';

//表单序列化
export const serialize = data => {
  let list = [];
  Object.keys(data).forEach(ele => {
    list.push(`${ele}=${data[ele]}`)
  })
  return list.join('&');
};
export const getObjType = obj => {
  var toString = Object.prototype.toString;
  var map = {
    '[object Boolean]': 'boolean',
    '[object Number]': 'number',
    '[object String]': 'string',
    '[object Function]': 'function',
    '[object Array]': 'array',
    '[object Date]': 'date',
    '[object RegExp]': 'regExp',
    '[object Undefined]': 'undefined',
    '[object Null]': 'null',
    '[object Object]': 'object'
  };
  if (obj instanceof Element) {
    return 'element';
  }
  return map[toString.call(obj)];
};
/**
 * 对象深拷贝
 */
export const deepClone = data => {
  var type = getObjType(data);
  var obj;
  if (type === 'array') {
    obj = [];
  } else if (type === 'object') {
    obj = {};
  } else {
    //不再具有下一层次
    return data;
  }
  if (type === 'array') {
    for (var i = 0, len = data.length; i < len; i++) {
      obj.push(deepClone(data[i]));
    }
  } else if (type === 'object') {
    for (var key in data) {
      obj[key] = deepClone(data[key]);
    }
  }
  return obj;
};
/**
 * 设置灰度模式
 */
export const toggleGrayMode = (status) => {
  if (status) {
    document.body.className = document.body.className + ' grayMode';
  } else {
    document.body.className = document.body.className.replace(' grayMode', '');
  }
};
/**
 * 设置主题
 */
export const setTheme = (name) => {
  document.body.className = name;
}

/**
 * 加密处理
 */
export const encryption = (params) => {
  let {
    data,
    type,
    param,
    key
  } = params;
  let result = JSON.parse(JSON.stringify(data));
  if (type == 'Base64') {
    param.forEach(ele => {
      result[ele] = btoa(result[ele]);
    })
  } else if (type == 'Aes') {
    param.forEach(ele => {
      result[ele] = window.CryptoJS.AES.encrypt(result[ele], key).toString();
    })

  }
  return result;
};


/**
 * 浏览器判断是否全屏
 */
export const fullscreenToggel = () => {
  if (fullscreenEnable()) {
    exitFullScreen();
  } else {
    reqFullScreen();
  }
};
/**
 * esc监听全屏
 */
export const listenfullscreen = (callback) => {
  function listen() {
    callback()
  }

  document.addEventListener("fullscreenchange", function () {
    listen();
  });
  document.addEventListener("mozfullscreenchange", function () {
    listen();
  });
  document.addEventListener("webkitfullscreenchange", function () {
    listen();
  });
  document.addEventListener("msfullscreenchange", function () {
    listen();
  });
};
/**
 * 浏览器判断是否全屏
 */
export const fullscreenEnable = () => {
  var isFullscreen = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen
  return isFullscreen;
}

/**
 * 浏览器全屏
 */
export const reqFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.documentElement.requestFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.documentElement.webkitRequestFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.documentElement.mozRequestFullScreen();
  }
};
/**
 * 浏览器退出全屏
 */
export const exitFullScreen = () => {
  if (document.documentElement.requestFullScreen) {
    document.exitFullScreen();
  } else if (document.documentElement.webkitRequestFullScreen) {
    document.webkitCancelFullScreen();
  } else if (document.documentElement.mozRequestFullScreen) {
    document.mozCancelFullScreen();
  }
};
/**
 * 递归寻找子类的父类
 */

export const findParent = (menu, id) => {
  for (let i = 0; i < menu.length; i++) {
    if (menu[i].children.length != 0) {
      for (let j = 0; j < menu[i].children.length; j++) {
        if (menu[i].children[j].id == id) {
          return menu[i];
        } else {
          if (menu[i].children[j].children.length != 0) {
            return findParent(menu[i].children[j].children, id);
          }
        }
      }
    }
  }
};
/**
 * 判断2个对象属性和值是否相等
 */

/**
 * 动态插入css
 */

export const loadStyle = url => {
  const link = document.createElement('link');
  link.type = 'text/css';
  link.rel = 'stylesheet';
  link.href = url;
  const head = document.getElementsByTagName('head')[0];
  head.appendChild(link);
};
/**
 * 判断路由是否相等
 */
export const diff = (obj1, obj2) => {
  delete obj1.close;
  var o1 = obj1 instanceof Object;
  var o2 = obj2 instanceof Object;
  if (!o1 || !o2) { /*  判断不是对象  */
    return obj1 === obj2;
  }

  if (Object.keys(obj1).length !== Object.keys(obj2).length) {
    return false;
    //Object.keys() 返回一个由对象的自身可枚举属性(key值)组成的数组,例如：数组返回下表：let arr = ["a", "b", "c"];console.log(Object.keys(arr))->0,1,2;
  }

  for (var attr in obj1) {
    var t1 = obj1[attr] instanceof Object;
    var t2 = obj2[attr] instanceof Object;
    if (t1 && t2) {
      return diff(obj1[attr], obj2[attr]);
    } else if (obj1[attr] !== obj2[attr]) {
      return false;
    }
  }
  return true;
}
/**
 * 根据字典的value显示label
 */
export const findByvalue = (dic, value) => {
  let result = '';
  if (validatenull(dic)) return value;
  if (typeof (value) == 'string' || typeof (value) == 'number' || typeof (value) == 'boolean') {
    let index = 0;
    index = findArray(dic, value);
    if (index != -1) {
      result = dic[index].label;
    } else {
      result = value;
    }
  } else if (value instanceof Array) {
    result = [];
    let index = 0;
    value.forEach(ele => {
      index = findArray(dic, ele);
      if (index != -1) {
        result.push(dic[index].label);
      } else {
        result.push(value);
      }
    });
    result = result.toString();
  }
  return result;
};
/**
 * 根据字典的value查找对应的index
 */
export const findArray = (dic, value) => {
  for (let i = 0; i < dic.length; i++) {
    if (dic[i].value == value) {
      return i;
    }
  }
  return -1;
};
/**
 * 生成随机len位数字
 */
export const randomLenNum = (len, date) => {
  let random = '';
  random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len ? len : 4);
  if (date) random = random + Date.now();
  return random;
};
/**
 * 打开小窗口
 */
export const openWindow = (url, title, w, h) => {
  // Fixes dual-screen position                            Most browsers       Firefox
  const dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left
  const dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top

  const width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width
  const height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height

  const left = ((width / 2) - (w / 2)) + dualScreenLeft
  const top = ((height / 2) - (h / 2)) + dualScreenTop
  const newWindow = window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left)

  // Puts focus on the newWindow
  if (window.focus) {
    newWindow.focus()
  }
}

export function discoloration(value, boolean, i = 0) {
  if (i > 5) {
    return
  }
  if (boolean) {
    if (value.parentNode.className === 'erp-list') {
      value.parentNode.setAttribute('style', 'background-color:#E9F3FD')
    } else {
      discoloration(value.parentNode, true, i += 1)
    }
  } else {
    if (value.parentNode.className === 'erp-list') {
      value.parentNode.setAttribute('style', 'background-color:#fff')
    } else {
      discoloration(value.parentNode, false, i += 1)
    }
  }
}


export function toNumber(arr) {
  arr.forEach((value) => {
    if (typeof value.id == 'string') {
      value.id = Number(value.id)
    }
  })
  return arr
}

export function dataToString(arr) {
  arr.forEach((value) => {
    if (typeof value.id == 'number') {
      value.id = value.id.toString()
    }
  })
  return arr
}

//创建补0函数
function p(s) {
  return s < 10 ? '0' + s : s;
}

export const changeTime = (time) => {
  let target = new Date(time);
  let year = target.getFullYear();
  let month = target.getMonth() + 1;
  let day = target.getDate();
  let hour = target.getHours();
  let minute = target.getMinutes();
  let second = target.getSeconds();
  return year + '-' + p(month) + '-' + p(day) + ' ' + p(hour) + ':' + p(minute) + ':' + p(second);
}
//判断时间大小
export const whoTime = (time) => {
  var startTime = time.replace("/-/g", "/");//时间转换
//时间
  var date1 = new Date(startTime);
//现在时间
  var date2 = new Date();
//判断时间是否过期
  return date1 < date2 ? true : false;
}

export const dealStr = (str) => {
  if (str) {
    return str.split(',')
  } else {
    return []
  }
}

//转换树形结构
export function dataCollation(arr) {
  arr.forEach((value) => {
    if (value.attributes.bladeUsers) {
      value.attributes.bladeUsers.forEach(key => {
        // key.dictKey = key.dictKey
        value.children.push(key)
      })
    }
  })
  return arr
}


export const removeChildren = (arr) => { // 去除树形结构的数据为空的children
  const test = [];
  arr.map(item => {
    if (item.hasOwnProperty('children') && item.children.length == 0) {
      delete item.children;
      test.push(item)
    } else {
      test.push(item)
      if (item.hasOwnProperty('children')) {
        removeChildren(item.children)
      }
    }
  })
  return test;
}

export const recursive = (arr, id) => {
  arr.forEach(value => {
    value.id == id
  })
}


export function getParent(data2, nodeId2) {
  var arrRes = [];
  if (data2.length == 0) {
    if (!!nodeId2) {
      arrRes.unshift(data2)
    }
    return arrRes;
  }
  let rev = (data, nodeId) => {
    for (var i = 0, length = data.length; i < length; i++) {
      let node = data[i];
      if (node.id == nodeId) {
        arrRes.unshift(node)
        rev(data2, node.parent_id);
        break;
      } else {
        if (!!node.children) {
          rev(node.children, nodeId);
        }
      }
    }
    return arrRes;
  };
  arrRes = rev(data2, nodeId2);
  return arrRes;
}

export function trim(str) { // 正则替换开头与结尾的空格
  const reg = /(^\s*)|(\s*$)/
  if (reg.test(str)) {
    return str
  } else {
    return str.replace(/(^\s*)|(\s*$)/g, "")
  }
}

//获取当前小时
export const getHour = () => {
  let hourEnd = '';
  let target = new Date();
  let hour = target.getHours();
  if (hour < 8) {
    hourEnd = '08:00'
  } else if (8 < hour < 24) {//9-23
    hourEnd = hour < 9 ? `0${hour + 1}:00` : `${hour + 1}:00`
  }
  return hourEnd;
}
//获取下周 - 可能值：周一，周二，周三
export const getNextDate = () => {
  let target = new Date();
  let day = target.getDay();//0-6
  if (day == 0) {//今天周日
    return '三'
  } else if (day == 6) {//今天周六
    return '二'
  } else {
    return '一'
  }
}
//获取当前月份 -  ["2019-09-1", "2019-10-25"]
export const getCurrentMonth = () => {
  let now = new Date();
  let year = now.getFullYear();
  let month = now.getMonth() + 1;//获取当前月份的日期
  let day = now.getDate();
  return year + "-" + p(month) + "-01;" + year + "-" + p(month) + "-" + p(day)
}
//获取今天  明天  后天
export const getDate = (AddDayCount) => {
  let dd = new Date();
  dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期
  let y = dd.getFullYear();
  let m = dd.getMonth() + 1;//获取当前月份的日期
  let d = dd.getDate();
  return y + "-" + p(m) + "-" + p(d);
}
//获取下周一，周二，周三
export const getNext = (target) => {
  var Stamp;
  Stamp = new Date();
  var num = 7 - Stamp.getDay() + target;
  Stamp.setDate(Stamp.getDate() + num);
  var year = Stamp.getFullYear(); //获取完整的年份(4位,1970-????)
  var month = Stamp.getMonth() + 1; //获取当前月份(0-11,0代表1月)
  var mvar = '';
  if (month < 10) {
    mvar = '0' + month;
  } else {
    mvar = month + '';
  }
  var day = Stamp.getDate();
  var dvar = '';
  if (day < 10) {
    dvar = '0' + day;
  } else {
    dvar = day + '';
  }
  return year + "-" + mvar + '-' + dvar
}

//获取当前时间
export const getTimeNow = () => {     	//获取时间
  var date = new Date();
  var year = date.getFullYear();
  var month = date.getMonth();
  var day = date.getDate();

  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();

  //这样写显示时间在1~9会挤占空间；所以要在1~9的数字前补零;
  if (hour < 10) {
    hour = '0' + hour;
  }
  if (minute < 10) {
    minute = '0' + minute;
  }
  if (second < 10) {
    second = '0' + second;
  }


  var x = date.getDay();//获取星期


  var time = year + '-' + month + '-' + day + '-' + hour + ':' + minute + ':' + second
  return time
}
export const verification = (str) => {
  // var cat = /[`~!@#$%^&*()\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）\-+={}|《》？：“”【】、；‘’，。、]/im
  var cat = /[<>&]/im
  return cat.test(str)
}
export const downTemplate = (content, fileName) => {
  const blob = new Blob([content]);
  const a = document.createElement("a");
  const url = window.URL.createObjectURL(blob);
  const filename = fileName;
  a.href = url;
  a.download = filename;
  a.click();
  window.URL.revokeObjectURL(url);
}
export const timeUTC = (i, d) => {
  //参数d为要转换的时间(Date类型)
  if (typeof i !== 'number') return;
  var len = d.getTime();
  //本地时间与GMT时间的时间偏移差
  var offset = d.getTimezoneOffset() * 60000;
  //得到现在的格林尼治时间
  var utcTime = len + offset;
  return formatTime(new Date(utcTime + 3600000 * i));
}

//格式化时间
function formatTime(time) {
  const d = new Date(time)
  const resDate = d.getFullYear() + '-' + p((d.getMonth() + 1)) + '-' + p(d.getDate())
  const resTime = p(d.getHours()) + ':' + p(d.getMinutes()) + ':' + p(d.getSeconds())
  var a = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
  var week = d.getDay();
  return resDate + " " + a[week] + " " + resTime;
}

export const getParams = (name) => {
  const reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  const search = window.location.hash.toString();
  const r = search.substr(search.indexOf('?') + 1).match(reg);
  return r == null ? "" : unescape(r[2]);
}
export const setCookie = (name, value) => {
  var Days = 0.5;
  var exp = new Date();
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
export const getCookie = (name) => {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");

  if (arr = document.cookie.match(reg))

    return unescape(arr[2]);
  else
    return null;
}
//筛选今天是工作日，节假日， -calendar
export const getTodayCalendar = (day) => {
  const today = day.substring(5, 10);
  calendar.map(item => {
    if (item.title == today) {
      return item.content
    }
  })
  //否则判断是什么日子
  const star = day.substring(11, 14);
  if (star == '星期天' || star == '星期六') {
    return '休息日'
  } else {
    return '工作日'
  }
}

export const nowDate = (lang, type) => {
  var now = new Date();
  var year = now.getFullYear(); //得到年份
  var month = now.getMonth();//得到月份
  var date = now.getDate();//得到日期


  if (month < 10) {
    month = '0' + month;
  }
  if (date < 10) {
    date = '0' + date;
  }

  var num = "";
  for (var i = 0; i < 2; i++) {
    num += Math.floor(Math.random() * 10)
  }

  return year + '' + month + '' + date + '-' + num + '-' + lang + '.' + type
}

export const getIp = (onNewIP) => {
//compatibility for firefox and chrome
  var myPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection;
  var pc = new myPeerConnection({
      iceServers: []
    }),
    noop = function () {
    },
    localIPs = {},
    ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g,
    key;

  function iterateIP(ip) {
    if (!localIPs[ip]) onNewIP(ip);
    localIPs[ip] = true;
  }

  //create a bogus data channel
  pc.createDataChannel("");

  // create offer and set local description
  pc.createOffer().then(function (sdp) {
    sdp.sdp.split('\n').forEach(function (line) {
      if (line.indexOf('candidate') < 0) return;
      line.match(ipRegex).forEach(iterateIP);
    });

    pc.setLocalDescription(sdp, noop, noop);
  }).catch(function (reason) {
    // An error occurred, so handle the failure to connect
  });

  //sten for candidate events
  pc.onicecandidate = function (ice) {
    if (!ice || !ice.candidate || !ice.candidate.candidate || !ice.candidate.candidate.match(ipRegex)) return;
    ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
  };
}
export const validateEmail = (email) => {
  // 邮箱验证正则
  var reg = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/;
  return reg.test(email);
}

function transferDate(date) {

  // 年
  var year = date.getFullYear();
  // 月
  var month = date.getMonth() + 1;
  // 日
  var day = date.getDate();

  if (month >= 1 && month <= 9) {

    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {

    day = "0" + day;
  }

  var dateString = year + '-' + month + '-' + day;

  return dateString;
}

const start = " 00:00:00"
const end = " 23:59:59"
//获取今天
export const getToady = () => {
  var day2 = new Date();
  var s2 = day2.getFullYear() + "-" + (day2.getMonth() + 1) + "-" + day2.getDate() + start;
  var time = new Date(s2).getTime();
  return time;
}
export const getYesterday = () => {
  var day1 = new Date();
  day1.setTime(day1.getTime() - 24 * 60 * 60 * 1000);
  var s1 = day1.getFullYear() + "-" + (day1.getMonth() + 1) + "-" + day1.getDate() + start;
  var time = new Date(s1).getTime();
  return time;
}
export const getNowWeek = () => {
  //按周日为一周的最后一天计算
  var date = new Date();
  //今天是这周的第几天
  var today = date.getDay();
  //上周日距离今天的天数（负数表示）
  var stepSunDay = -today + 1;
  // 如果今天是周日
  if (today == 0) {
    stepSunDay = -7;
  }
  // 周一距离今天的天数（负数表示）
  var stepMonday = 7 - today;
  var time = date.getTime();
  var monday = new Date(time + stepSunDay * 24 * 3600 * 1000);
  var sunday = new Date(time + stepMonday * 24 * 3600 * 1000);
  //本周一的日期 （起始日期）
  var startDate = transferDate(monday) + start; // 日期变换
  //本周日的日期 （结束日期）
  var endDate = transferDate(sunday) + end; // 日期变换
  return {
    startDate: new Date(startDate).getTime(),
    endDate: new Date(endDate).getTime(),
  }
}
export const getNowMonth = () => {
// 获取当前月的第一天
  var start1 = new Date();
  start1.setDate(1);

  // 获取当前月的最后一天
  var date = new Date();
  var currentMonth = date.getMonth();
  var nextMonth = ++currentMonth;
  var nextMonthFirstDay = new Date(date.getFullYear(), nextMonth, 1);
  var oneDay = 1000 * 60 * 60 * 24;
  var end1 = new Date(nextMonthFirstDay - oneDay);

  var startDate = transferDate(start1) + start; // 日期变换
  var endDate = transferDate(end1) + end; // 日期变换
  return {
    startDate: new Date(startDate).getTime(),
    endDate: new Date(endDate).getTime(),
  }
}
export const nextOneHour = (time) => {
  var date = new Date(time);
  var tt = date.getTime();
  var ntt = tt + 60 * 60 * 1000;
  var dtt = new Date(ntt);
  var d = new Date(dtt);
  var youWant = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
  return youWant
}
export const filterEmailHttp = (type) => {
  switch (parseInt(type)) {
    case 0:
      return 'IMAP';
      break;
    case 1:
      return 'POP';
      break;
    case 2:
      return 'Exchange';
      break;
    default:
      return 'IMAP'
  }
}

/*
* 跳转到不同的图表页
* */
export const isUSA = (basename) => {
  if (basename == 'Gail' || basename.indexOf("GAIL") != -1 || basename.indexOf("UK_L") != -1) {
    return ''
  } else if (basename == 'usa') {
    return '/customs/table'
  } else {
    return '/customs/exitTable'
  }
}
export const hs8 = (basename) => {
  var b = false;
  switch (basename) {
    case "PhilippinesB_ex":
      b = true;
      break;
    case "Germany_B_im":
      b = true;
      break;
    case "Germany_B_ex":
      b = true;
      break;
    case "Japan_B_im":
      b = true;
      break;
    case "Japan_B_ex":
      b = true;
      break;
    case "Spain_B_im":
      b = true;
      break;
    case "Spain_B_ex":
      b = true;
      break;
    case "Italy_B_im":
      b = true;
      break;
    case "Italy_B_ex":
      b = true;
      break;
    case "Britain_B_im":
      b = true;
      break;
    case "Britain_B_ex":
      b = true;
      break;

    case "France_B_im":
      b = true;
      break;
    case "France_B_ex":
      b = true;
      break;
    case "Belgium_B_im":
      b = true;
      break;
    case "Belgium_B_ex":
      b = true;
      break;
    case "Netherlands_B_im":
      b = true;
      break;
    case "Netherlands_B_ex":
      b = true;
      break;
    case "United_Arab_Emirates_B_im":
      b = true;
      break;
    case "United_Arab_Emirates_B_ex":
      b = true;
      break;
    case "Egypt_B_im":
      b = true;
      break;
    case "Egypt_B_ex":
      b = true;
      break;

    case "Canada_B_im":
      b = true;
      break;
    case "Canada_B_ex":
      b = true;
      break;
    case "Singapore_B_im":
      b = true;
      break;
    case "Singapore_B_ex":
      b = true;
      break;
    case "Australia_B_im":
      b = true;
      break;
    case "Australia_B_ex":
      b = true;
      break;
    case "Bangladesh_B_im":
      b = true;
      break;
    case "Bangladesh_B_ex":
      b = true;
      break;
    case "Saudi_Arabia_B_im":
      b = true;
      break;
    case "Saudi_Arabia_B_ex":
      b = true;
      break;

    case "Nepal_B_im":
      b = true;
      break;
    case "Nepal_B_ex":
      b = true;
      break;
    case "Malaysia_B_im":
      b = true;
      break;
    case "Malaysia_B_ex":
      b = true;
      break;
    case "Korea_B_im":
      b = true;
      break;
    case "Korea_B_ex":
      b = true;
      break;
    case "Poland_B_im":
      b = true;
      break;
    case "Poland_B_ex":
      b = true;
      break;
    case "Thailand_B_im":
      b = true;
      break;
    case "Thailand_B_ex":
      b = true;
      break;
    case "Switzerland_B_im":
      b = true;
      break;
    case "Switzerland_B_ex":
      b = true;
      break;
    case "Taiwan_B_im":
      b = true;
      break;
    case "Taiwan_B_ex":
      b = true;
      break;
  }
  return b;
}
//获得国旗地址名称
export const fragSRC = (row) => {
  const str = row.col1;
  if (str.indexOf('所罗门群岛') != -1) {
    return 'SolomonIslands';
  } else if (str.indexOf('圣多美和普林西比') != -1) {
    return 'SaoTomeAndPrincipe';
  } else if (str.indexOf('法属圭亚那') != -1) {
    return 'FrenchGuiana';
  } else if (str.indexOf('沙特阿拉伯') != -1) {
    return 'SaudiArabia';
  } else if (str.indexOf('法属波利尼西亚') != -1) {
    return 'FrenchPolynesia';
  } else if (str.indexOf('几内亚比绍') != -1) {
    return 'GuineaBissau';
  } else if (str.indexOf('新喀里多尼亚') != -1) {
    return 'NewCaledonia';
  } else if (str.indexOf('新几内亚') != -1) {
    return 'NewGuinea';
  } else if (str.indexOf('新西兰') != -1) {
    return 'NewZealand';
  } else if (str.indexOf('刚果共和国') != -1) {
    return 'RepublicOfCongo';
  } else if (str.indexOf('南苏丹') != -1) {
    return 'RepublicOfSouthSudan';
  } else if (str.indexOf('斯里兰卡') != -1) {
    return 'SriLanka';
  } else if (str.indexOf('圣赫勒拿岛') != -1) {
    return 'StHelena';
  } else if (str.indexOf('圣基茨和尼维斯') != -1) {
    return 'StKittsNevis';
  } else if (str.indexOf('圣卢西亚') != -1) {
    return 'Saint-Luci';
  } else if (str.indexOf('圣卢西亚') != -1) {
    return 'Saint-Luci';
  } else if (str.indexOf('法属圣马丁岛') != -1) {
    return 'StMartin';
  } else if (str.indexOf('圣皮埃尔和密克隆群岛') != -1) {
    return 'StPierreandMiquelon';
  } else if (str.indexOf('圣文森特和格林纳丁斯') != -1) {
    return 'StVincentTheGrenadines';
  } else if (str.indexOf('多米尼克国') != -1) {
    return 'TheCommonwealthOfDominica';
  } else if (str.indexOf('斯威士') != -1) {
    return 'Swaziland';
  } else if (str.indexOf('阿拉伯联合酋长国') != -1) {
    return 'UnitedArabEmirates';
  } else if (str.indexOf('美属维尔京群岛') != -1) {
    return 'UnitedStatesVirginIslands';
  } else {
    return row.col2.split(" ")[0];
  }
}

export const getSum = (total, num) => {
  return total + num;
}
export const dealFileSize = (size) => {
  size = size.toString();
  if (size.indexOf('KB') != -1 || size.indexOf('B') != -1 || size.indexOf('MB') != -1
    || size.indexOf('kb') != -1 || size.indexOf('b') != -1 || size.indexOf('mb') != -1) {
    return size;
  }
  let result = parseInt(size / 1024);
  if (result > 1024) {
    return parseInt(result / 1024) + 'M';
  }
  return result + 'KB';
}

function getDay() {
  var d = new Date();
  var my_day = d.getDate();
  var my_month = d.getMonth() + 1;
  var my_year = d.getFullYear();
  return `${my_year}-${my_month}-${my_day}`
}

export const fileTypeStr = (params, long) => {
  var end = `<div><br><br><p data-start="${long}"></p><div style="border: 1px solid #EAF0F6;width: 30rem;margin-bottom: 1rem">
    <div style="padding: 1rem .5rem">
        <p style="font-size: 1.2rem;color: #666;margin: 0;padding: 0;color:#000">Sent you some files</p>
    </div>
    <div style="background-color: #87cefa24;border-top: 1px solid #ddd;    padding: .5rem;">
        <h1 style="padding-bottom:.25rem;font-size: 1rem;font-weight:500;border-bottom: 1px solid #ddd">Large attachment(${long+1})</h1>
        <div style="display: flex;justify-content: space-between;align-items: center">
            <div>
                <h2 style="font-size: .8rem;font-weight:500;color: #232323;margin-bottom: 5px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap">${params.picName}</h2>
                <p style="font-size: .7rem;color: #666;margin: 0;padding: 0;">${dealFileSize(params.fileSize)} &nbsp;&nbsp;&nbsp; Expiration Date: ${formatTimeThree()}</p>
            </div>
            <a href="${params.fileGuid}" target="_blank" style="text-decoration: none;background: #2A97F9;color: #fff;padding: 0 .6rem;height: 1.8rem;line-height: 1.8rem;border-radius: 2px;">Download</a>
        </div>
    </div>
</div><b data-end="${long}"></b></div>`
  return end;
}
export const dealFileType = (name) => {
  name = name.toLowerCase();
  //截取类型
  let index = name.lastIndexOf(".");
  let fileName = "." + name.substr(index + 1);
  let images = ['.jpg', '.jpeg', '.png', '.gif'];
  let videos = ['.avi', '.mp4', '.wav', '.rm', '.rmvb', '.mov', '.dat', '.wmv', '.3gp', '.amv', '.dmv', '.flv'];
  let files = ['.ppt', '.pptx', '.pdf', '.doc', '.psd', '.txt', '.xls', '.xlsx', '.eml'];
  //图片判断
  if (images.includes(fileName)) {
    return 1
  } else if (videos.includes(fileName)) {
    return 2
  } else if (files.includes(fileName)) {
    switch (fileName) {
      case '.ppt':
        return 'icon-ppt';
      case '.pptx':
        return 'icon-ppt';
      case '.pdf':
        return 'icon-pdf'
      case '.doc':
        return 'icon-doc'
      case '.psd':
        return 'icon-psd'
      case '.txt':
        return 'icon-txt'
      case '.xlsx':
        return 'icon-xlsx'
      case '.xls':
        return 'icon-xlsx'
      case '.eml':
        return 'icon-EML'
      default:
        return 'icon-folder'
    }
  } else {
    return 'icon-doc'
  }
}

function getTimeByDay() {
  let today = new Date().getTime()
  return today + 60 * 60 * 1000 * 24 * 30;
}

export const formatTimeThree = () => {
  return new Date(getTimeByDay()).toISOString().split('T')[0];
}

export const filterSameEmail = (target) => {
  var result = [];
  for (let i = 0, len = target.length; i < len; i++) {
    let item = target[i];
    item.state = 0;
    for (let j = 0, len1 = store.state.common.emailList.length; j < len1; j++) {
      const item1 = store.state.common.emailList[j];
      if (item.email == item1.emailAddr) {//匹配
        item.state = 1;
      }
    }
    result.push(item)
  }
  return result;
}
/**
 * 下属  - 跳转下属模式
 *
 * 我的客户 - 跳转客户模式
 * */
export const getCustomerEmail = (...param) => {
  let params = {allEmailList: param[0]},type=param[2],userID=param[1].userId;
  params = {...params, ...param[1]};
  relation(params).then(res => {
    if (res.data.success) {
      const result = res.data.data;
      if (JSON.stringify(result)!='{}') {//存在
        //添加到- 1:客户模式 / 0:下属模式
        let name='',target='',ID='',path='',state='',email='';
        if(type){
          ID = param[0][0];
          name = 'emailListCustomerTab';
          target='SET_EMAILLISTCUSTOMERTAB';
          state=4;
          path=`/mail/mailCustomer/${param[0][0]}`
          email = ID;
        }else {
          ID ='0';
          name = 'emailListNextTab';
          target='SET_EMAILLISTNEXTTAB';
          path=`/mail/underling/${userID}/${params.allEmailList[0]}`;
          state=0;
          email = '';
          store.commit('SET_ISFRAG', 8)
        }
        if (getDiffList(ID,name) == -1) {
          store.commit(target, {
            type: 1, row: {
              id: ID,
              title: email,
              state:state,
              close: true
            }
          })
        }else{
          store.commit(target, {type:0,current:ID})
        }
        router.push(path)
      } else {
        Message({
          message: '暂无往来邮件',
          type: 'success'
        });
      }
    }
  })
}

export const getDictory = (name) => {
  const list = store.state.common.commonUnits;
  let target = {children: []};
  for (let item of list) {
    if (item.code == name) {
      target = item;
    }
  }
  return target;
}
export const getRollbackID = (tree, targetID, parent = 'pid') => {
  let parentList = []

  function buildParentList(arr) {
    arr.forEach(g => {
      if (g[parent] != undefined) {
        let pid = g[parent]
        let oid = g['id']
        parentList[oid] = pid
      }
      if (g.children != undefined && g.children.length != 0)
        buildParentList(g['children'])
    })
  }

  buildParentList(tree)
  let arr = []
  var newArr = []

  function findParent(idx) {
    if (parentList[idx] != undefined) {
      let pid = parentList[idx]
      arr.push(pid)
      findParent(pid)
    } else {
      arr.reverse()
      arr.splice(0, 1)
      newArr = arr
    }
  }

  findParent(targetID)
  newArr.push(targetID)
  return newArr;
}
export const filterProduct = (content, row) => {
  //数据字段替换
  let waitContent = content;//待替换内容
  const columnList = store.state.common.columnList;//原始数据源
  for (let item of columnList) {
    let title = item.title;
    let str = ''
    if (waitContent.indexOf(title) != -1) {//找到了对应项
      if (title == '[产品图片]') {
        str = `<img src="${row[item.column]}" style="width: 95%;margin: 0 auto;display: block" alt="">`
      } else {
        //规格  column 包含 . 表示规格内部取值 ，  unit 内部包含 . 表示规格内部取值
        let col = '', unit = '';
        if (item.column.indexOf(".") != -1) {
          const endCol = item.column.split(".")[1];
          col = row.productSpec[endCol];
        } else {
          col = row[item.column];
        }
        if (item.hasOwnProperty('unit')) {
          if (item.unit.indexOf(".") != -1) {
            const endCol = item.unit.split(".")[1];
            unit = row.productSpec[endCol];
          } else {
            unit = row[item.unit];
          }
        } else if (item.hasOwnProperty('unitDemo')) {
          unit = item.unitDemo;
        }
        str = col + unit;
      }
      title = title.substring(1, title.length - 1);
      waitContent = waitContent.replace(new RegExp(title, 'g'), str);
    }
  }
  waitContent = waitContent.replace(/\[/g, " ");
  waitContent = waitContent.replace(/\]/g, " ");
  return waitContent;
}

function getEnd(text, tree, column) {
  let frag = false;
  const long = tree.length;
  for (let i = 0; i < long; i++) {
    const item = tree[i];
    const lastItem = tree[long - 1];
    if (lastItem[column] == text) {//匹配最后一个是否
      frag = true;
    } else {
      if (item.hasOwnProperty('children')) {
        getEnd(text, item.children, column)
      }
    }
  }
  return frag
}

export const getTreeEnd = (tree, column) => {
  //循环元对象 state
  let index = 1;
  function getIndex(option) {
    for (let i = 0, len = option.length; i < len; i++) {
      let item = option[i];
      if (item[column] == '自建目录'||item[column] == '公司目录') {
        index = 1;
      }
      item.isfile = getEnd(item[column], option, column);
      item.state = index;
      if (item.hasOwnProperty('children')) {
        index++;
        getIndex(item.children)
      } else {
        if (i == len - 1) {
          index = index - 1;
        }
      }
    }
  }

  getIndex(tree);
}
export const getTargetMenuID = (name) => {
  var option = store.state.user.topMenu, ID = '';
  for (let item of option) {
    if (item.name == name) {
      ID = item.id
    }
  }
  return ID;
}
export const getDiffList = (id, name) => {
  let index = -1;
  const row = store.state.common[name];
  for (let i in row.list) {
    const item = row.list[i];
    if (item.id == id) {
      index = i;
    }
  }
  return index;
}

export const removeCurrentTab=(tab,targetName,currentID)=>{
  let list = store.state.common[tab].list, arr = [], index;
  for (let i in list) {
    const item = list[i];
    if (item.id != currentID) {
      arr.push(item)
    } else {
      index = i;
    }
  }
  console.log(targetName,arr,index,currentID)
  store.commit(targetName, {
    type: 2, list: arr, index: index
  })
}

export const getTimeEmailList = (list) => {
  let today = [], yesterday = [], nowWeek = [], month = [], previous = [], data = [];
  let weekT = getNowWeek();
  let monthT = getNowMonth();
  let todayTime = getToady(),//今天
    yesterdayTime = getYesterday(),//昨天
    weekStartTime = weekT.startDate,
    monthStartTime = monthT.startDate,
    monthEndTime = monthT.endDate;
  list.forEach((item, index) => { //sendTime
    const time = new Date(item.sendTime).getTime();
    // 判断是否是  更早
    if (todayTime <= time) { //今天
      today.push(item);
    } else if ((yesterdayTime <= time) && (time < todayTime)) {//昨天
      yesterday.push(item);
    } else if ((weekStartTime < time) && (time < yesterdayTime)) {//本周
      nowWeek.push(item);
    } else if ((monthStartTime < time) && (time < monthEndTime)) {//本月
      month.push(item);
    } else if (time < monthStartTime) {//更早
      previous.push(item);
    }
  })
  //插入数组
  data.push({title: '今天', list: today, total: `${today.length}`})
  data.push({title: '昨天', list: yesterday, total: `${yesterday.length}`})
  data.push({title: '本周', list: nowWeek, total: `${nowWeek.length}`})
  data.push({title: '本月', list: month, total: `${month.length}`})
  data.push({title: '更早', list: previous, total: `${previous.length}`});
  return data;
}
export const filterTopMenu = (list) => {
  list.forEach(value => {
    switch (value.name) {
      case '客户':
        value.menuType = 'customer'
        break
      case '邮件':
        value.menuType = 'mail'
        break
      case '产品':
        value.menuType = 'product'
        break
      case '订单':
        value.menuType = 'order'
        break
      case '营销自动化':
        value.menuType = 'automation'
        break
      case '海关数据':
        value.menuType = 'ocean'
        break
      case '云文件管理':
        value.menuType = 'file'
        break
      case '服务系统管理':
        value.menuType = 'setUp'
        break
      case '系统管理':
        value.menuType = 'setUp'
        break
      case '官网':
        value.menuType = 'website'
        break
    }
  })
  return list.filter(item=>{
    return item.name!='服务系统管理';
  });
}
export const expireLogin = () => {
  store.commit('resetAllState');//重置state
  store.commit('set_isExpire',true);//设置过期
  router.replace("/login");
}
//根据名称获取对应的id
export const getTargetFolderID = (arr,path) => {
  let ID='';
  function getID(arr) {
    for(let i=0,len=arr.length;i<len;i++){
      const item = arr[i];
      if(item['path']==path){
        ID= item.id;
      }else if(item.hasOwnProperty('children')){
        getID(item.children);
      }
    }
  }
  getID(arr);
  return ID;
}

//根据客户名称获取对应的id
export const getCustID = (arr,path) => {
  let ID='';
  function getID(arr) {
    for(let i=0,len=arr.length;i<len;i++){
      const item = arr[i];
      if(item['name']==path){
        ID= item.id;
      }else if(item.hasOwnProperty('children')){
        getID(item.children);
      }
    }
  }
  getID(arr);
  return ID;
}


// 消息提醒
export const popNotice = (item) => {
  if (Notification.permission == "granted") {
    var notification = new Notification(item.title, {
      body: item.content,
      // icon: './img/popNoticeLogo.png',
      icon: './img/login/logo.png',
      requireInteraction: true,
      isClickble: true
    });

    notification.onclick = () => {
      switch (item.messageType) {
        case 0:
          router.push(`/message/detail/${item.id}`)
          break;
        case 2:
          dealEmail(item)
          break;
        case 3:
          dealEmail(item)
          break;
        case 5:
          router.push({
            path: '/mail/approval/apply/detail',
            query:{
              id: item.contentId
            }
          })
          break;
        case 6:
          router.push('/customer/admin/3')
          break;
      }
      notification.close();
    };
  }
}

function dealEmail(item) {
  const ID = item.contentId+"a";
  //收件箱 2
  let target='',path='',name='',frag='';
  if(item.messageType == 2){
    target = 'SET_EMAILLISTTAB';
    path ='/mail/index';
    name = 'emailListTab';
    frag =0;
  }else{
    target = 'SET_EMAILLISTPENDINGTAB';
    path ='/mail/pending/index';
    name = 'emailListPendingTab';
    frag =1;
  }
  if (getDiffList(ID,name)==-1) {
    store.commit(target, {
      type: 1, row: {
        id: ID,
        title: item.content,
        state:1,
        close: true
      }
    })
  }else{
    store.commit(target, {type:0,current:ID})
  }

  // console.log(path)
  router.push({path:path})
  sessionStorage.setItem("lastpath", path)
  store.commit('SET_ISFRAG', frag)
}

// 时间计算

var minute = 1000 * 60;
var hour = minute * 60;
var day = hour * 24;
var halfamonth = day * 15;
var month = day * 30;

export const timeAgo = (dateTimeStamp)=> {
  if(dateTimeStamp==undefined){

    return false;
  }else{
    dateTimeStamp = dateTimeStamp.replace(/\-/g, "/");

    var sTime = new Date(dateTimeStamp).getTime();//把时间pretime的值转为时间戳

    var now = new Date().getTime();//获取当前时间的时间戳

    var diffValue = now - sTime;

    if(diffValue < 0){
      console.log("结束日期不能小于开始日期！");
    }

    var monthC =diffValue/month;
    var weekC =diffValue/(7*day);
    var dayC =diffValue/day;
    var hourC =diffValue/hour;
    var minC =diffValue/minute;

    if(monthC>=1){
      return parseInt(monthC) + "个月前"
    }
    else if(weekC>=1){
      return parseInt(weekC) + "周前"
    }
    else if(dayC>=1){
      return parseInt(dayC) +"天前"
    }
    else if(hourC>=1){
      return parseInt(hourC) +"个小时前"
    }
    else if(minC>=1){
      return parseInt(minC) +"分钟前"
    }else{
      return "刚刚"
    }
  }
}

